﻿using EasyLoger.Configuration;
using System;
using System.IO;
using System.Xml;
namespace EasyLoger
{
    internal class FileLoger : ILoger
    {
        private FileLogConfig config;
        private StreamWriter writer;
        public FileLoger(XmlNode node)
        {
            this.config = new FileLogConfig(node);
        }
        public void Write(LogMessage msg)
        {
            this.CheckSize();
            this.OpenFile();
            this.writer.WriteLine(msg.Message + "\t" + msg.Date.ToString());
            this.writer.Flush();
            this.CloseFile();
        }
        private void CheckSize()
        {
            FileInfo fileInfo1 = new FileInfo(this.config.FilePath);
            if (!Directory.Exists(fileInfo1.DirectoryName))
            {
                Directory.CreateDirectory(fileInfo1.DirectoryName);
                fileInfo1 = null;
            }
            if (!File.Exists(this.config.FilePath))
            {
                File.Create(this.config.FilePath);
            }
            else
            {
                FileInfo fileInfo = new FileInfo(this.config.FilePath);
                if (fileInfo.Length > 2097152L)
                {
                    fileInfo.MoveTo(this.config.FilePath.ToLower().Replace(".txt", "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"));
                    File.Create(this.config.FilePath);
                }
                fileInfo = null;
            }
        }
        private void OpenFile()
        {
            this.writer = new StreamWriter(this.config.FilePath, true);
        }
        private void CloseFile()
        {
            this.writer.Close();
        }
        public void Stop()
        {
        }
    }
}
